import json
import socket
from urllib.parse import quote


class RobotTCPClient:
    def __init__(self, host="192.168.43.108", port=31001):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(3)  # 设置超时防止阻塞
        self.sock.connect((host, port))

    def send_command(self, cmd, params=None, uuid=""):
        # 构建符合协议要求的指令字符串
        full_cmd = cmd
        if params:
            full_cmd += "?" + "&".join(
                [f"{k}={quote(str(v))}" for k, v in params.items()]
            )
        if uuid:
            full_cmd += (
                f"&uuid={quote(uuid)}" if "?" in full_cmd else f"?uuid={quote(uuid)}"
            )

        # 发送指令
        self.sock.sendall(f"{full_cmd}".encode("utf-8"))

        # 接收完整响应
        buffer = b""
        while True:
            try:
                data = self.sock.recv(4096)
                if not data:
                    break
                buffer += data
                # 尝试解析JSON
                return json.loads(buffer.decode("utf-8"))
            except (json.JSONDecodeError, socket.timeout):
                continue


# 使用示例
if __name__ == "__main__":
    robot = RobotTCPClient()

    # 获取WiFi列表
    print("WiFi列表:", robot.send_command("/api/wifi/info"))

    # # 连接WiFi（含特殊字符示例）
    # params = {
    #     "SSID": "200",  # 含空格需要编码
    #     "password": "55555555",
    # }
    # print("连接结果:", robot.send_command("/api/wifi/connect", params))
